package com.yh.csx.demo.service;

import java.util.Date;
import java.util.Objects;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yh.csx.bsf.shardingjdbc.base.DataSource;
import com.yh.csx.demo.dao.CustomerMapper;
import com.yh.csx.demo.model.po.Customer;
import com.yh.csx.demo.model.request.CustomerAddReq;
import com.yh.csx.demo.model.vo.User;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CustomerService {

	@Autowired
	private CustomerMapper customerMapper;

	/**
	 * 获取客户详细信息
	 * 
	 * @param id
	 * @return
	 */
	@DataSource(name="main0")
	public Customer getCustomer(Long id) {
		Customer customer = null;
		customer = customerMapper.selectByPrimaryKey(id);
		customer.setUpdateTime(new Date());

		return customer;
	}

	/**
	 * 修改客户信息
	 * 
	 * @param customer
	 */
	//@DataSource(name="main0")
	public void modify(Customer customer) {
		customerMapper.updateByPrimaryKey(customer);
	}

	/**
	 * 新增客户(保存草稿)
	 * 
	 * @param req
	 * @throws Exception 
	 */
	@DataSource(name="main0")
	public Customer addCustomer(User user, CustomerAddReq req) throws Exception {
		Customer customer =new Customer();
		BeanUtils.copyProperties(req, customer);			
		Customer beforCustomer = null;
		if (Objects.nonNull(req.getId())
				&& Objects.nonNull(beforCustomer = customerMapper.selectByPrimaryKey(req.getId()))) {
			if (customerMapper.selectCountByCustomerName(req.getCustomerName(), req.getId()) > 0) {
				throw new Exception("客户名称已存在");
			}
			
			
			customerMapper.updateByPrimaryKeySelective(beforCustomer);
			return beforCustomer;
		} else {
			if (customerMapper.selectCountByCustomerName(req.getCustomerName(), null) > 0) {
				throw new Exception("客户名称已存在");
			}
			this.initCustomer(user, customer);		
			if (log.isDebugEnabled()) {
				log.debug("入库客户信息" + customer.toString());
			}
			customerMapper.insertSelective(customer);
			return customer;
		}
	}

	/**
	 * 初始化客户默认值
	 * 
	 * @param user
	 * @param customer
	 */
	private void initCustomer(User user, Customer customer) {	
		
		customer.setCreateBy(user.getUserName());
		
	}


}
